package cn.kgc.shiro.controller;

import cn.kgc.shiro.entity.User;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 课工场
 * @date 2023/11/21
 * @description
 */
@RestController
@RequestMapping("users")
public class UserController {


    @GetMapping("login")
    public Map<String, Object> login(User user) {
        HashMap<String, Object> map = new HashMap<>();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), user.getPassword());

        try {
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            map.put("code", 500);
            map.put("message", "用户名错误");
            return map;
        } catch (IncorrectCredentialsException e) {
            map.put("code", 500);
            map.put("message", "密码错误");
            return map;
        }

        map.put("code", 200);
        map.put("message", "登录成功");
        return map;
    }


    @RequestMapping("delete/{id}")
    public Map<String, Object> delete(@PathVariable("id") Integer id) {

        // 编程式权限控制
        Subject subject = SecurityUtils.getSubject();
        boolean b = subject.hasRole("super");
        HashMap<String, Object> map = new HashMap<>();
        if (b) {
            map.put("code", 200);
            map.put("id", id);
            map.put("message", "删除成功");
            return map;
        } else {
            map.put("code", 403);
            map.put("message", "没有权限，请联系管理员");
            return map;
        }


    }


    @RequestMapping("update")
    @RequiresRoles("root")    // 基于角色的判定
    // @RequiresPermissions("sys:user:update")    基于权限字符串的判定
    public Map<String, Object> update(User user) {

        HashMap<String, Object> map = new HashMap<>();

        map.put("code", 200);
        map.put("message", "编辑成功");
        return map;
    }



    @RequestMapping("unAuthenticated")
    public Map<String, Object> unAuthenticated() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 401);
        map.put("message", "请认证后访问");
        return map;
    }

}
